package com.msun.auth.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Description //TODO
 * @Date 2023/3/30 10:51
 * @Author guijie
 **/
@EnableAsync
@Configuration
public class AsyncConfig {
    private int corePoolSize = Runtime.getRuntime().availableProcessors()*2;
    private int maxPoolSize = Runtime.getRuntime().availableProcessors()*4;
    private int queueCapacity = 1024;
    private String namePrefix = "async-";

    @Bean
    public Executor asyncThreadPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setThreadNamePrefix(namePrefix);
        //当pool达到了maxSize，CallerRunsPolicy表示不在新线程中执行任务，而是在调用者所在线程内执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}
